package com.danco.training.zaneuskaya.controller.book;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.danco.training.zaneuskaya.api.BookService;
import com.danco.training.zaneuskaya.controller.GenericController;
import com.danco.training.zaneuskaya.domain.Book;
import com.danco.training.zaneuskaya.service.impl.BookServiceImpl;

@SuppressWarnings("serial")
public class BookEditController extends GenericController {
	
private BookService bookService;
private SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

	public BookEditController() {
		super();
		bookService = BookServiceImpl.getBookStorageSeviceImplInstance();

	}
	


	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("id");

		if (id != null && !id.isEmpty()) {
			Book book = bookService.getById(Integer.parseInt(id));
			request.setAttribute("book", book);
			request.setAttribute("pub_date", formatter.format(book.getPublicationDate()));
		}

		
		getServletContext().getRequestDispatcher("/WEB-INF/views/book/edit.jsp").forward(
				request, response);

	}
	
	protected void doPut(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String id = request.getParameter("id");
		String title = request.getParameter("book_title");
		String author = request.getParameter("book_author");
		
		String pubDate = request.getParameter("pub_date");
		Date publicationDate = null;
		try {
			publicationDate = formatter.parse(pubDate);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		double price = Double.parseDouble(request.getParameter("book_price"));
		int quantity = Integer.parseInt(request.getParameter("book_quantity"));

		Book book = new Book(title, author, publicationDate, price, true,
				quantity, new Date());
		
		if (id == null || id.isEmpty()) {
			bookService.addEntity(book);
		} else {
			book.setBookId(Integer.parseInt(id));
			bookService.updateEntity(book);
		}

		response.sendRedirect(request.getContextPath() + "/book/info?id="+ id );
				
	}
	
	@Override
		protected void doPost(HttpServletRequest req, HttpServletResponse resp)
				throws ServletException, IOException {
			
			doPut(req, resp);
		}
	
	
}
